const express = require('express');
const { buildSchema } = require('graphql');
const { graphqlHTTP } = require('express-graphql');
const { cmd } = require('./db');

const schema = buildSchema(`
  input UserInput {
    "姓名"
    name: String
    "年龄"
    age: Int
  }
  type User {
    "ID"
    id: ID,
    "姓名"
    name: String,
    "年龄"
    age: Int
  }
  type Query {
    "获取所有用户"
    getUsers: [User]
    "获取单个用户信息"
    getUser(id: ID!): User
  }
  type Mutation {
    "创建用户"
    createUser(user: UserInput): Int
    "更新用户"
    updateUser(id: ID!, user: UserInput): Int
    "删除用户"
    deleteUser(id: ID!): Boolean
  }
`);

const root = {
  async getUsers() {
    const { results } = await cmd('SELECT id, name, age FROM user');
    return results;
  },
  async getUser({ id }) {
    const { results } = await cmd(
      'SELECT id, name, age FROM user WHERE id = ?',
      [id]
    );
    return results[0];
  },
  async createUser({ user }) {
    const id = Math.random().toString(16).substr(2);
    const data = { id, ...user };
    const {
      results: { affectedRows },
    } = await cmd('INSERT INTO user SET ?', data);
    return affectedRows;
  },
  async updateUser({ id, user }) {
    const {
      results: { affectedRows },
    } = await cmd('UPDATE user SET ? WHERE id = ?', [user, id]);
    return affectedRows;
  },
  async deleteUser({ id }) {
    const {
      results: { affectedRows },
    } = await cmd('DELETE FROM user WHERE id = ?', [id]);
    return affectedRows;
  },
};

const app = express();

app.use(
  '/api/graphql',
  graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true,
  })
);

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(express.static('public'));

app.listen(3000, () => {
  console.log('server is running in http://localhost:3000/api/graphql');
});
